<HTML> <head> <TITLE>Synchronization Locks Library for D</TITLE> </head>
<body> 
<h1>Synchronization Locks for D</h1>
Locks is a library of synchronization constructs for the D
programming language based on the concurrent locks library
by Doug Lea. 
For more info about D see <a
href="http://www.digitalmars.com/d/">DigitalMars D home page</a>.  The
library can be downloaded 
<a href="http://home.comcast.net/~benhinkle/locks/locks.zip">here</a>
or as part of 
<a href="http://home.comcast.net/~benhinkle/mintl">MinTL</a>.  
For more information about the Java library see
<a href="http://gee.cs.oswego.edu/dl/concurrency-interest/index.html">
JSR-166</a>. For an initial port see
<a href="http://www.dsource.org/projects/concurrent"> dsource</a>.

<p>
This library is in the public domain.
Portions written by Ben Hinkle, 2004, portions ported from code
written by Doug Lea.
Email comments and bug reports to ben.hinkle@gmail.com
<p>

<h3> Overview</h3>

The D language has builtin support for defining critical sections 
using the <tt>synchronized</tt> statement but does not include
POSIX synchronization constructs like locks and condition variables.
The purpose of the Locks library is to extend the builtin D
capabilities to support not only POSIX constructs but also support
latches, barriers and exchangers. Concurrent containers like queues,
stacks and associative arrays are in the MinTL library in the
package <tt>mintl.concurrent</tt>. When using concurrent algorithms
be careful to use the <tt>volatile</tt> statement to ensure data
is properly updated in all the threads.

<p>
The primary interface of the Locks library is the Lock interface. It
defines two methods, <tt>lock</tt> and <tt>unlock</tt>, that aquire
and release the lock.  In general the Lock interface makes no
guarentee that a thread can <tt>lock</tt> a lock that it already
owns. The <tt>ReentrantLock</tt> class, which implements
<tt>Lock</tt>, does guarantee that the thread that hold the lock can
call <tt>lock</tt> without blocking. If a thread calls <tt>lock</tt>
and the lock is held by another thread then the calling thread is
parked until the lock is released. The <tt>tryLock</tt> functions
attempts to acquire the lock immediately or within a specified time interval.
For example a typical
class <tt>X</tt> that uses a <tt>ReentrantLock</tt> to control access
to function <tt>m</tt> uses try-finally blocks to insure the lock is
released before the function returns:

<pre>
  class X {
    private ReentrantLock lock;
    // ...
    this() { 
      lock = new ReentrantLock; 
    }
    void m() { 
      lock.lock();  // block until lock is available
      try {
        // ... method body
      } finally {
        lock.unlock()
      }
    }
  }
</pre>
A <tt>ScopedLock</tt> can simplify the code around managing locks. 
The class <tt>X</tt> could instead use a <tt>ScopedLock</tt> 
in <tt>m</tt>:
<pre>
  class X {
    private ReentrantLock lock;
    // ...
    this() { 
      lock = new ReentrantLock; 
    }
    void m() { 
        auto ScopedLock slock = new ScopedLock(lock);
        // ... method body
    }
  }
</pre>

The only difference between the two implementations is that the
<tt>ScopedLock</tt>, as written, will allocate memory from the GC each
time it is called.

<p>
The Condition interface defines a condition variable for a given lock.
A condition variable allows two or more threads to hand-off ownership
of the lock atomically by calling <tt>wait</tt> and <tt>notify</tt>.
If a thread owns the lock and calls <tt>wait</tt>
on a condition variable then the thread releases the lock and
blocks until notified by the condition variable.
Once notified the thread attempts to acquire the lock and once successful
continues execution. The wait function accepts timeout values to stop
blocking after a certain amount of time. A thread that fails the timeout
still must reacquire the lock before proceeding. A typical use of condition
variables is to signal when an event has happened. 
The function <tt>Lock.newCondition</tt> creates and returns a Condition
instance.
For example, the
condition below signals when the <tt>data</tt> variable has been set:
<pre>
  int data;
  Thread getter, setter;
  ReentrantLock lock = new ReentrantLock;
  Condition is_ready = lock.newCondition;
  setter = new Thread(
    delegate int() {
      lock.lock();
      try {
        data = 10;
        is_ready.notify();
      } finally {
        lock.unlock();
      }
      return 0;
    });
  getter = new Thread(
    delegate int() {
      lock.lock();
      try {
        is_ready.wait();
        printf("%d\n",data);
      } finally {
        lock.unlock();
      }
      return 0;
    });
  getter.start();
  setter.start();
</pre>

<p>
To start several threads and have them wait until a signal from a
coordinating thread use a <tt>CountDownLatch</tt> with a count of
1. For example, 
<pre>
  CountDownLatch go = new CountDownLatch(1);
  Thread[4] t;
  for (int i=0; i < 4; i++) {
    t[i] = new Thread(
      delegate int() {
        go.wait(); // wait for signal from main thread
        // ... do something interesting ...
        return 0;
      });
    t[i].start();
  }
  go.countDown(); // let worker threads go
</pre>
Conversely to signal a coordinating thread that the worker threads
are finished have each worker thread decrement another 
<tt>CountDownLatch</tt>:
<pre>
  CountDownLatch go = new CountDownLatch(1);
  CountDownLatch allDone = new CountDownLatch(4);
  Thread[4] t;
  for (int i=0; i < 4; i++) {
    t[i] = new Thread(
      delegate int() {
        go.wait(); // wait for signal from main thread
        // ... do something interesting ...
        allDone.countDown();
        return 0;
      });
    t[i].start();
  }
  go.countDown(); // let worker threads go
  allDone.wait(); // wait for all workers to finish
</pre>

<p>
A <tt>CyclicBarrier</tt> is similar to a <tt>CountDownLatch</tt>
except the cyclic barrier is used without a controlling thread.
A thread that reaches the barrier waits until the barrier count
is exhausted before continuing. Once the barrier is tripped it
optionally runs a function and resets to zero. Continuing the
example from the previous paragraph the worker threads might need
to rendezvous at a certain point mid-way through their task:
<pre>
  CountDownLatch go = new CountDownLatch(1);
  CountDownLatch allDone = new CountDownLatch(4);
  CyclicBarrier barrier = new CyclicBarrier(4);
  Thread[4] t;
  for (int i=0; i < 4; i++) {
    t[i] = new Thread(
      delegate int() {
        go.wait(); // wait for signal from main thread
        // ... do something interesting ...
        barrier.wait(); // wait for all workers to get to barrier
        // ... do something else interesting ...
        allDone.countDown();
        return 0;
      });
    t[i].start();
  }
  go.countDown(); // let worker threads go
  allDone.wait(); // wait for all workers to finish
</pre>

<p>
A <tt>Semaphore</tt> maintains a given number of permits. When a 
thread acquires a permit the semaphore decremements the number of
available permits and when a thread releases the permit (any thread
can release the permit) the semaphore increments the number of
available permits. Semaphores don't have a concept of threads
owning permits - it only gives out and recieves permits atomically.
A typical use case for semaphores is to manage access by multiple
threads to a fixed collection of objects.

<h3> API Reference</h3>
This section lists the public structs and functions in the library without 
detailed explanation. For more information see the documentation before
the function or class in the source file.
The API is organized by module:<br>
<dl>
<dt><a href="#condition">locks.condition</a>
<dt><a href="#countdown">locks.countdown</a>
<dt><a href="#exchanger">locks.exchanger</a>
<dt><a href="#lock">locks.lock</a>
<dt><a href="#platformutils">locks.platformutils</a>
<dt><a href="#readwritelock">locks.readwritelock</a>
<dt><a href="#reentrantlock">locks.reentrantlock</a>
<dt><a href="#semaphore">locks.semaphore</a>
<dt><a href="#timeunit">locks.timeunit</a>
</dl>


<a name="condition">
<h4>locks.condition</h4>
<dl>
<dt>interface <b>Condition</b>
<dd>A condition variable
<p>
<dl>
<dt>void <b>wait</b>()
<dd>Cause current thread to wait until notified
<dt>long <b>waitNanos</b>(long nanosTimeout)
<dd>Cause current thread to wait until notified or time expires
<dt>bool <b>wait</b>(long time, TimeUnit unit)
<dd>Cause current thread to wait until notified or time expires
<dt>void <b>notify</b>()
<dd>Wake up one waiting thread
<dt>void <b>notifyAll</b>()
<dd>Wake up all waiting threads
</dl>
</dl>

<a name="countdown">
<h4>locks.countdown</h4>
<dl>
<dt>class <b>CountDownLatch</b>
<dd>Allow one or more threads to wait for a set of other threads.
<p>
<dl>
<dt><b>this</b>(int count)
<dd>Construct the latch with the given count before releasing
<dt>void <b>wait</b>()
<dd>Causes the current thread to wait until the count reaches zero
<dt>void <b>wait</b>(long timeout, TimeUnit unit)
<dd>Causes the current thread to wait until the count reaches zero or time expires
<dt>void <b>countDown</b>()
<dd>Decrement count
<dt>long <b>count</b>
<dd>Get the current count
<dt>char[] <b>toString</b>
<dd>Return a string summary of the latch
</dl>
</dl>

<a name="cyclicbarrier">
<h4>locks.cyclicbarrier</h4>
<dl>
<dt>class <b>CyclicBarrier</b>
<dd>Allow a fixed group of threads to wait for each other
<p>
<dl>
<dt><b>this</b>(int parties, int delegate() barrierAction = null)
<dd>Construct the barrier with given number of parties and concluding action
<dt>int <b>parties</b>
<dd>Return number of parties for this barrier
<dt>int <b>wait</b>()
<dd>Causes the current thread to wait for all parties to reach the barrier
<dt>int <b>wait</b>(long timeout, TimeUnit unit)
<dd>Causes the current thread to wait only for the specified time
<dt>bool <b>isBroken</b>()
<dd>Returns true if the barrier has been broken
<dt>void <b>reset</b>()
<dd>Break the barrier for waiting parties and reset to initial state
<dt>int <b>getNumberWaiting</b>
<dd>Get the current number of waiting parties
</dl>
</dl>

<a name="exchanger">
<h4>locks.exchanger</h4>
<dl>
<dt>class <b>Exchanger</b>(Value)
<dd>Allow two threads to safely exchange values.
<p>
<dl>
<dt><b>this</b>()
<dd>Construct the exchanger
<dt>Value <b>exchange</b>(Value v)
<dd>Offer v for exchange and wait for response
<dt>Value <b>exchange</b>(Value v, long timeout, TimeUnit unit)
<dd>Offer v for exchange and wait for response with possible timeout
</dl>
</dl>

<a name="lock">
<h4>locks.lock</h4>
<dl>
<dt>interface <b>Lock</b>
<dd>The interface for all lock implementations.
<p>
<dl>
<dt>void <b>lock</b>()
<dd>Acquires the lock
<dt>bool <b>tryLock</b>()
<dd>Acquires the lock only if it is free at the time of invocation
<dt>bool <b>tryLock</b>(long time, TimeUnit unit)
<dd>Acquires the lock if it is free within the given waiting time
<dt>void <b>unlock</b>()
<dd>Releases the lock
<dt>Condition <b>newCondition</b>
<dd>Returns a new Condition instance that is bound to this lock instance
</dl>
</dl>
<dl>
<dt>auto final class <b>ScopedLock</b>
<dd>An auto class for aquiring and releasing a lock in a scope
<p>
<dl>
<dt><b>this</b>(Lock lock)
<dd>Initializes the ScopedLock and acquires the supplied lock
<dt><b>~this</b>()
<dd>Release the lock
</dl>
</dl>

<a name="platformutils">
<h4>locks.platformutils</h4>
<dl>
<dt>bit <b>compareAndSet32</b>(void* mem, void* expect, void* update)
<dd>Compare the 32 bit value expect with the value at *mem and if equal
set to update and return true. This assumes a pointer is 32 bits.
<dt>bit <b>compareAndSet32</b>(void* mem, int expect, int update)
<dd>Convenience overload for compareAndSet32 when the data are integers
instead of pointers
<dt>bit <b>compareAndSet64</b>(void* mem, void* expect, void* update)
<dd>Compare the 64 bit value at *expect with the value at *mem and if equal
set to *update and return true.
<dt>int <b>atomicAdd32</b>(int* val, int x);
<dd>Atomically add x to *val and return previous value of *val
<dt>int <b>atomicExchange32</b>(int* val, int x);
<dd>Atomically store x to *val and return previous value of *val
<dt>void <b>atomicInc32</b>(int* val);
<dd>Atomically increment *val
<dt>void <b>atomicDec32</b>(int* val);
<dd>Atomically decrement *val
<dt>long <b>currentTimeMillis</b>()
<dd>Return the current system time in milliseconds
<dt>long <b>currentTimeNanos</b>()
<dd>Return the current system time in nanoseconds
<dt>void <b>sleepNanos</b>(long duration)
<dd>Sleep the current thread for the specified duration in nanoseconds
</dl>

<a name="readwritelock">
<h4>locks.readwritelock</h4>
<dl>
<dt>interface <b>ReadWriteLock</b>
<dd>A pair of read-write locks
<p>
<dl>
<dt>Lock <b>readLock</b>()
<dd>Return the read lock
<dt>Lock <b>writeLock</b>()
<dd>Return the write lock
</dl>
</dl>
<p>
<dl>
<dt>class <b>ReentrantReadWriteLock</b> : ReadWriteLock
<dd>A pair of reentrant read-write locks
<p>
<dl>
<dt><b>this</b>(bool fair = false)
<dd>Construct the lock with specified fairness policy
<dt>Lock <b>readLock</b>()
<dd>Return the read lock
<dt>Lock <b>writeLock</b>()
<dd>Return the write lock
</dl>

</dl>

<a name="reentrantlock">
<h4>locks.reentrantlock</h4>
<dl>
<dt>class <b>ReentrantLock</b> : Lock
<dd>A reentrant mutual exclusive lock with condition variables
<p>
<dl>
<dt><b>this</b>(bool fair = false)
<dd>Construct the lock with specified fairness policy
<dt>void <b>lock</b>()
<dd>Acquires the lock
<dt>bool <b>tryLock</b>()
<dd>Acquires the lock only if it is free at the time of invocation
<dt>bool <b>tryLock</b>(long time, TimeUnit unit)
<dd>Acquires the lock if it is free within the given waiting time
<dt>void <b>unlock</b>()
<dd>Releases the lock
<dt>Condition <b>newCondition</b>
<dd>Returns a new Condition instance that is bound to this lock instance
<dt>int <b>getHoldCount</b>()
<dd>Get the number of holds on this lock by the current thread
<dt>bool <b>isHeldByCurrentThread</b>()
<dd>Query if the lock is held by the current thread
<dt>bool <b>isLocked</b>()
<dd>Query if the lock is held by any thread
<dt>bool <b>isFair</b>()
<dd>Query if the lock is fair
<dt>char[] <b>toString</b>()
<dd>return a string representation of the lock
</dl>

</dl>

<a name="semaphore">
<h4>locks.semaphore</h4>
<dl>
<dt>class <b>Semaphore</b>
<dd>A counting semaphore for maintaining a set of permits
<p>
<dl>
<dt><b>this</b>(int permits, bool fair = false)
<dd>Construct the semaphore with the given number of permits and fairness policy
<dt>void <b>acquire</b>(int permits = 1)
<dd>Acquires n permits, blocking until all are available
<dt>bool <b>tryAcquire</b>(int permits = 1)
<dd>Acquires n permit from this semaphore only if they are immediately available
<dt>bool <b>tryAcquire</b>(long timeout, TimeUnit unit, int permits = 1)
<dd>Attempt acquiring n permits within the specified time interval
<dt>void <b>release</b>(int permits = 1)
<dd>Release n permits
<dt>int <b>availablePermits</b>
<dd>Get the current number of available permits
<dt>bool <b>isFair</b>()
<dd>return true if the semaphore is fair
<dt>char[] <b>toString</b>
<dd>Return a string summary of the semaphore
</dl>

</dl>

<a name="timeunit">
<h4>locks.timeunit</h4>
<dl>
	<dt>enum <b>TimeUnit</b>
	<dd>Time units common in synchronization
	    <dl>
	    <dt><b>NanoSeconds = 0</b>
	    <dt><b>MicroSeconds</b>
	    <dt><b>MilliSeconds</b>
	    <dt><b>Seconds</b>
	    </dl>
	<p>
<dt>long <b>convert</b>(long duration, TimeUnit fromUnit, TimeUnit toUnit);
<dd>Convert the given time duration in the given unit to this unit.
<dt>long <b>toNanos</b>(long duration, TimeUnit fromUnit);
<dd>Convert to nanoseconds.
<dt>long <b>toMicros</b>(long duration, TimeUnit fromUnit);
<dd>Convert to microseconds.
<dt>long <b>toMillis</b>(long duration, TimeUnit fromUnit);
<dd>Convert to milliseconds.
<dt>long <b>toSeconds</b>(long duration, TimeUnit fromUnit);
<dd>Convert to seconds.
</dl>

</BODY>
</HTML>
